<script setup>
import PageContainer from "@/components/PageContainer/index.vue";
import appTable from "@/components/i-table/t-able.vue";
import {
  getUserListService,
  reqAddOrUpdate,
  reqRemoveUser,
  reqChangeUserStatus,
  reqAllRole,
  reqSetUserRole,
} from "@/api/user";

import { reactive, ref, onMounted, h, resolveComponent, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

onMounted(() => {
  getList();
});
const handleUser = async (row) => {
  Object.assign(UserParams, row);
  let { code, result } = await reqAllRole(row.id);
  if (code == 0) {
    roles.value = result.allRolesList;
    checkedRoles.value = result.assignedRoles.map((role) => role.id) || [];

    // 检查是否所有角色都被选中
    const isAllSelected = checkedRoles.value.length === roles.value.length;
    checkAll.value = isAllSelected;
    isIndeterminate.value = checkedRoles.value.length > 0 && !isAllSelected;

    drawer2.value = true;
  }
};
// 全选按钮
const handleCheckAllChange = (val) => {
  checkedRoles.value = val ? roles.value.map((role) => role.id) : [];
  isIndeterminate.value = false;
};
// 复选框按钮
const handleCheckedCitiesChange = (value) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === roles.value.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < roles.value.length;
};
const confirmRole = async () => {
  let data = {
    userId: UserParams.id,
    roleIdList: checkedRoles.value,
  };
  let res = await reqSetUserRole(data);
  if (res.code == 0) {
    drawer2.value = false;
    resetRoleStates();
    ElMessage({
      type: "success",
      message: "更新成功",
    });
    getList();
  }
  console.log(data);
};

const changeUserStatus = async (events, params) => {
  try {
    await ElMessageBox.confirm(
      `你确认${events ? "启用" : "禁用"}用户:${params.user_name}吗？`,
      "温馨提示",
      {
        type: "warning",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
      }
    );
    await reqChangeUserStatus(params.id, { status: Number(events) });
    ElMessage({
      type: "success",
      message: `${events ? "启用" : "禁用"}成功`,
    });
    getList();
  } catch (error) {
    console.log(error);
  }
};
const confirmClick = async () => {
  try {
    await ruleFormRef.value?.methods.validate();

    let res = await reqAddOrUpdate(UserParams);
    if (res.code == 0) {
      drawer.value = false;
      ElMessage({
        type: "success",
        message: UserParams.id ? "更新成功" : "添加成功",
      });
      // userlist(UserParams.id ? pageNo.value : 1)
      window.location.reload();
    } else {
      ElMessage({
        type: "error",
        message: UserParams.id ? "更新失败" : "添加失败",
      });
    }
  } catch (error) {
    console.log(error);
  }
};
//取消
const cancelClick = () => {
  Object.assign(UserParams, {
    email: "",
    user_name: "",
    password: "",
    id: "",
  });
  nextTick(() => {
    ruleFormRef.value.methods.clearValidate();
  });
  drawer.value = false;
};

const getList = async () => {
  let params = Object.assign({}, queryParams, tableContent.pagination);
  console.log(tableContent.pagination, params);
  tableContent.options.loading = true;
  try {
    const { code, result } = await getUserListService(params);
    console.log(result);
    tableContent.list = result.list || [];
    tableContent.total = result.total;
    tableContent.options.loading = false;
  } catch (error) {
    console.log(error);
    tableContent.options.loading = false;
  }
};

// 切换每页显示的数量
const handleSizeChange = (pagination) => {
  console.log("pagination", pagination);
  Object.assign(tableContent.pagination, pagination);
  getList();
};
// 切换页码
const handleIndexChange = (pagination) => {
  console.log("pagination", pagination);
  tableContent.pagination = pagination;
  getList();
};

const deleteUser = async (row) => {
  await ElMessageBox.confirm(
    `你确认删除用户:${row.user_name}吗？`,
    "温馨提示",
    {
      type: "warning",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
    }
  );

  await reqRemoveUser(row.id);

  ElMessage({ type: "success", message: "删除成功" });
  tableContent.list.length > 1
    ? (tableContent.pagination.pageNum = 1)
    : (tableContent.pagination.pageNum = tableContent.pagination.pageNum - 1);
  getList();
};

const handleQuery = () => {
  getList();
};
const resetQuery = () => {
  try {
    formRenderer.value.resetFields();
    Object.assign(queryParams, {
      user_name: "",
    });
    Object.assign(tableContent.pagination, { pageNum: 1, pageSize: 10 });
    getList();
  } catch (error) {
    console.log(error);
  }
};

// 表格
let tableContent = reactive({
  total: 0,
  list: [],
  otherHeight: 150,
  columns: [
    {
      prop: "id",
      label: "用户id",
      align: "center",
    },
    {
      prop: "user_name",
      label: "用户名称",
      align: "center",
    },
    {
      prop: "email",
      label: "用户邮箱",
      align: "center",
    },
    {
      prop: "roleName",
      label: "用户角色",
      align: "center",
      formatter: (row) => {
        return row.st_Roles.map((role) => role.role_name).join(",") || "--";
      },
    },
    {
      prop: "status",
      label: "状态",
      align: "center",
      width: "160",
      render: ({ row }) => {
        return h(resolveComponent("el-switch"), {
          size: "default",
          modelValue: Boolean(row.status),
          onChange: (events) => {
            changeUserStatus(events, row);
            // console.log(events);
          },
        });
      },
    },
    {
      prop: "createdAt",
      label: "创建时间",
      align: "center",
    },
    {
      prop: "updatedAt",
      label: "更新时间",
      align: "center",
    },
  ], // 需要展示的列
  options: {
    stripe: true, // 是否为斑马纹 table
    loading: false, // 是否添加表格loading加载动画
    highlightCurrentRow: true, // 是否支持当前行高亮显示
    mutiSelect: false, // 是否支持列表项选中功能
    border: true, //是否显示边框
    numbers: true, //是否显示序号
  }, // table 的参数
  pagination: {
    pageSizes: [2, 4, 6, 8],
    pageNum: 1,
    pageSize: 10,
  }, // 分页参数
  operates: {
    width: 200,
    list: [
      {
        label: "编辑",
        plain: true,
        method: (index, row) => {
          drawer.value = true;
          Object.assign(UserParams, row);
        },
      },
      {
        label: "删除",
        plain: true,
        method: (index, row) => {
          deleteUser(row);
        },
      },
      {
        label: "分配角色",
        plain: true,
        method: (index, row) => {
          handleUser(row);
        },
      },
    ],
  },
});

let UserParams = reactive({
  email: "",
  user_name: "",
  password: "",
});
const queryParams = reactive({});

const formRenderer = ref();
const drawer = ref(false);
const ruleFormRef = ref();
const content = reactive([
  {
    type: "input",
    id: "user_name",
    label: "用户名称",
  },
]);
const userContent = reactive([
  {
    type: "input",
    id: "email",
    label: "用户邮箱",
    rules: [{ required: true, message: "请输入用户邮箱", trigger: "blur" }],
  },
  {
    type: "input",
    id: "user_name",
    label: "用户名称",
    rules: [{ required: true, message: "请输入用户名称", trigger: "blur" }],
  },
  {
    type: "input",
    id: "password",
    label: "用户密码",
    rules: [{ required: true, message: "请输入用户密码", trigger: "blur" }],
    hidden: (form) => {
      return form.id ? true : false;
    },
  },
]);
const drawer2 = ref(false);
const checkAll = ref(false);
const isIndeterminate = ref(true);
const checkedRoles = ref([]);
const roles = ref([]);

const resetRoleStates = () => {
  checkAll.value = false;
  isIndeterminate.value = false;
  checkedRoles.value = [];
  roles.value = [];
};
</script>
<template>
  <div>
    <page-container title="用户管理">
      <template #extra>
        <el-button type="primary" @click="drawer = true" v-has="`btn.User.add`"
          >新增用户</el-button
        >
      </template>
      <el-form-renderer
        label-width="100px"
        :content="content"
        ref="formRenderer"
        style="padding-right: 30px"
        v-model:FormData="queryParams"
        class="render-form"
      >
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery"> 重置 </el-button>
      </el-form-renderer>

      <app-table
        :list="tableContent.list"
        :total="tableContent.total"
        :otherHeight="tableContent.otherHeight"
        :options="tableContent.options"
        :pagination="tableContent.pagination"
        :columns="tableContent.columns"
        :operates="tableContent.operates"
        @handleSizeChange="handleSizeChange"
        @handleIndexChange="handleIndexChange"
      >
      </app-table>
    </page-container>
    <!-- 弹窗 -->
    <el-drawer v-model="drawer" @close="cancelClick">
      <template #header>
        <h4 v-if="!UserParams.id">添加用户</h4>
        <h4 v-else>更新用户</h4>
      </template>
      <template #default>
        <el-form-renderer
          label-width="100px"
          :content="userContent"
          ref="ruleFormRef"
          style="padding-right: 30px"
          v-model:FormData="UserParams"
        >
        </el-form-renderer>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="confirmClick">确定</el-button>
        </div>
      </template>
    </el-drawer>
    <el-drawer v-model="drawer2" @close="resetRoleStates">
      <template #header>
        <h4>分配角色</h4>
      </template>

      <template #default>
        <el-form>
          <el-form-item label="用户姓名">
            <el-input disabled v-model="UserParams.user_name" />
          </el-form-item>
          <el-form-item label="用户角色">
            <div class="checkbox-container">
              <div class="checkbox-all">
                <el-checkbox
                  v-model="checkAll"
                  :indeterminate="isIndeterminate"
                  @change="handleCheckAllChange"
                >
                  全选
                </el-checkbox>
              </div>
              <!-- 显示职位的的复选框 -->
              <el-checkbox-group
                v-model="checkedRoles"
                @change="handleCheckedCitiesChange"
              >
                <el-checkbox
                  v-for="(role, index) in roles"
                  :key="index"
                  :label="role.role_name"
                  :value="role.id"
                >
                  {{ role.role_name }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer2 = false">取消</el-button>
          <el-button type="primary" @click="confirmRole">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<style scoped>
.from {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.checkbox-container {
  display: flex;
  flex-direction: column;
  gap: 3px;
}

.checkbox-all {
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
  margin-bottom: 10px;
}
</style>
